<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class ImportAreaData extends Command
{
    protected function configure()
    {
        $this->setName('import:area')
            ->setDescription('Import area data from local JSON file');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $output->writeln('Starting to import area data...');

            // 读取本地 JSON 文件
            $jsonPath = __DIR__ . '/area.json';
            if (!file_exists($jsonPath)) {
                throw new \Exception("Area data file not found: {$jsonPath}");
            }

            $jsonContent = file_get_contents($jsonPath);
            $data = json_decode($jsonContent, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new \Exception('Failed to parse JSON: ' . json_last_error_msg());
            }

            // 开始事务
            Db::startTrans();
            
            try {
                // 清空原有数据
                Db::table('area')->delete(true);
                
                // 导入省级数据
                foreach ($data['children'] as $province) {
                    // 插入省份
                    $provinceId = Db::table('area')->insertGetId([
                        'area_name' => $province['name'],
                        'area_code' => $province['code'],
                        'parent_id' => 0,
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s')
                    ]);

                    // 导入市级数据
                    if (!empty($province['children'])) {
                        foreach ($province['children'] as $city) {
                            // 插入城市
                            $cityId = Db::table('area')->insertGetId([
                                'area_name' => $city['name'],
                                'area_code' => $city['code'],
                                'parent_id' => $provinceId,
                                'create_time' => date('Y-m-d H:i:s'),
                                'update_time' => date('Y-m-d H:i:s')
                            ]);

                            // 导入区县级数据
                            if (!empty($city['children'])) {
                                foreach ($city['children'] as $district) {
                                    // 插入区县
                                    Db::table('area')->insert([
                                        'area_name' => $district['name'],
                                        'area_code' => $district['code'],
                                        'parent_id' => $cityId,
                                        'create_time' => date('Y-m-d H:i:s'),
                                        'update_time' => date('Y-m-d H:i:s')
                                    ]);
                                }
                            }
                        }
                    }
                }

                // 提交事务
                Db::commit();
                $output->writeln('Area data import completed successfully!');
                
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }

        } catch (\Exception $e) {
            $output->writeln('<error>Error: ' . $e->getMessage() . '</error>');
            return 1;
        }

        return 0;
    }
} 